package com.scs.application.core.mvc.controller;

import com.scs.application.core.utils.Encodes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Validator;

/**
 */
@Slf4j
public abstract class BaseController {


    @Autowired
    protected Validator validator;

    /**
     * 服务端参数有效性验证
     *
     * @param object 验证的实体对象
     * @param groups 验证组，不传入此参数时，同@Valid注解验证
     * @return 验证成功：继续执行；验证失败：抛出异常跳转400页面。
     */
//    protected void beanValidator(Object object, Class<?>... groups) {
//        BeanValidators.validateWithException(validator, object, groups);
//    }
    public HttpServletRequest request() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public HttpServletResponse response() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    /**
     * 设置下载参数/请求头
     *
     * @param fileName 文件名，例如  用户信息.xlsx
     */
    protected void setDownloadParam(String fileName) {
        response().setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response().setHeader("Content-Disposition", "attachment; filename=" + Encodes.urlEncode(fileName));


        // 设置浏览器可以获取到的请求头，以便axios端进行文件名统一处理
        response().setHeader("Access-Control-Expose-Headers", "Content-FileName");
        response().setHeader("Content-FileName", Encodes.urlEncode(fileName));
    }



}
